<?php

namespace App\Business\BLL;

use App\Models\LuckMoneyLog;
use App\Models\LuckMoneyRule;
use App\Models\LuckMoneyTimeRule;
use App\Models\UserWallet;
use Carbon\Carbon;

class LuckMoneyBLL
{
    public function getLuckMoney($game)
    {
        $now = Carbon::now();
        $today = Carbon::today();
        $currentTime = $now->toTimeString();

        //查询总规则
        $rule = $this->getRule($game->city, $now->toDateString(), $currentTime);
        if ($rule === false) {
            //该地区没有红包
            return ['recode' => 20, 'msg' => '当前地区没有乒乓币'];
        }
        // //检查时间范围
        // if ($rule->stime >= $currentTime || $currentTime >= $rule->etime) {
        //     return ['recode' => 30, 'msg' => "红包发放时间:$rule->stime-$rule->etime"];
        // }

        //检查结算间隔
        $diffSettleSec = abs($now->diffInSeconds($game->created_at));
        if ($diffSettleSec < $rule->settle_inv) {
            return ['recode' => 60, 'msg' => "结算频繁无乒乓币"];
        }

        //查询今天用户获取过的红包
        $lastTime = LuckMoneyLog::where([['created_at', '>', $today], ['status', 2], ['user_id', $game->play_a]])
            ->latest()
            ->first();
        $time = 0;
        $total = 0;
        if ($lastTime) {
            //检查时间间隔
            $diffSec = abs($now->diffInSeconds($lastTime->created_at));
            if ($diffSec < $rule->interval) {
                $nextTime = Carbon::parse($lastTime->created_at)->addSeconds($rule->interval);
                return ['recode' => 40, 'msg' => "乒乓币将于「 $nextTime 」到达"];
            }
            $time = $lastTime->time;
            $total = $lastTime->total;
        }
        $time++;
        //查询当次抽奖规则
        $timeRule = LuckMoneyTimeRule::where('rule_id', $rule->id)
            ->where([['start', '<=', $time], ['end', '>=', $time]])
            ->first();
        if ($timeRule) {
            $lower = $timeRule->lower;
            $upper = $timeRule->upper;
            //获取红包金额
            $money = rand($lower, $upper);
            $left = $rule->daily_user_upper - $total;
            $left = $left > $rule->min_amount ? $left : $rule->min_amount;
            $money = $left > $money ? $money : $left;
            if ($money > 0) {
                $total += $money;
                //保存记录
                $newLog = new LuckMoneyLog;
                $newLog->game_id = $game->id;
                $newLog->user_id = $game->play_a;
                $newLog->rule_id = $rule->id;
                $newLog->time = $time;
                $newLog->money = $money;
                $newLog->total = $total;
                //保存
                $newLog->save();
                if (empty($rule->bg)) {
                    $bg = config('set.luck_money_bg');
                } else {
                    $disk = \Storage::disk('qiniu');
                    $bg = $disk->url($rule->bg);
                }

                return ['recode' => 10, 'log' => $newLog, 'bg' => $bg];
            } else {
                return ['recode' => 50, 'msg' => '您今天乒乓币已经抽光了，请明天再来'];
            }
        } else {
            return ['recode' => 50, 'msg' => '您今天乒乓币已经抽光了，请明天再来'];
        }
    }

    public function confirmLuckMoney($id)
    {
        $ret = \DB::transaction(function () use ($id) {
            //查询记录
            $log = LuckMoneyLog::find($id);
            if (!$log) {
                return ['recode' => 0, 'msg' => '没有找到乒乓币'];
            }
            if ($log->status == 2) {
                return ['recode' => 0, 'msg' => '该乒乓币已经领取'];
            } else if ($log->status == 0) {
                return ['recode' => 0, 'msg' => '该乒乓币已经作废'];
            }
            //更新规则中总额
            LuckMoneyRule::where('id', $log->rule_id)->increment('current_amount', $log->money);
            //更新个人金额
            $userWallet = UserWallet::firstOrCreate(
                ['user_id' => $log->user_id], ['money' => 0]
            );
            $userWallet->money += $log->money;
            $userWallet->save();
            //变更状态
            $log->status = 2;
            $log->save();
            return ['recode' => 1, 'msg' => '领取成功'];
        });
        return $ret;
    }

    private function getRule($city, $date, $currentTime)
    {
        $city = substr($city . '000000', 0, 6);
        $rule = LuckMoneyRule::where([['city', $city], ['is_on', 1]])
            ->where([['sdate', '<=', $date], ['edate', '>=', $date]])
            ->where([['stime', '<=', $currentTime], ['etime', '>=', $currentTime]])
            ->whereRaw('total_upper>current_amount')
            ->latest()
            ->first();

        if ($rule) {
            return $rule;
        }
        if ($city == '000000') {
            return false;
        }

        $city = rtrim($city, '0');
        if (strlen($city) % 2 === 1) {
            $city = $city . '0';
        }
        $city = substr($city, 0, -2);

        return $this->getRule($city, $date, $currentTime);

    }
}
